/*******************************************************************************
 * Copyright (c) 2000, 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package edu.uts.reekie.designer.model.commands;

import java.util.Iterator;
import java.util.Vector;

import org.eclipse.gef.commands.Command;


import edu.uts.reekie.designer.*;
import edu.uts.reekie.designer.model.*;

public class ConnectionCommand
	extends Command
{

protected ViewNode oldSource;
protected ViewNode oldTarget;
protected ViewNode source;
protected ViewNode target; 
protected AbstractConnector connector;


public ConnectionCommand() {
	super(Messages.ConnectionCommand_Label);
}

public boolean canExecute(){
	
	if (source==null && target==null)
		return false;
	
	// disallow source -> source connections
	if (source.equals(target)) {
		return false;
	}
	// return false, if the source -> target connection exists already
	for (Iterator<ViewElement> iter = source.getSourceConnections().iterator(); iter.hasNext();) {
		ViewElement next = iter.next();
		
		if (next instanceof AbstractConnector) {
			AbstractConnector conn = (AbstractConnector) next;
			if (conn.getTarget().equals(target)) {
				return false;
			}
		}
	}
	return true;
}

public void execute() {
	
	
	connector.disconnect();
	connector.reconnect(source, target);

	if (source == null && target == null){
		connector.disconnect();
	}
}

public String getLabel() {
	return Messages.ConnectionCommand_Description;
}

public ViewNode getSource() {
	return source;
}



public ViewNode getTarget() {
	return target;
}


public AbstractConnector getConnector() {
	return connector;
}

public void redo() { 
	execute(); 
}

public void setSource(ViewNode newSource) {
	source = newSource;
}



public void setTarget(ViewNode newTarget) {
	target = newTarget;
}



public void setConnector(AbstractConnector c) {
	this.connector = c;
	oldSource = c.getSource();
	oldTarget = c.getTarget();
}

public void undo() {
	source = connector.getSource();
	target = connector.getTarget();

	connector.disconnect();
	connector.reconnect(oldSource,oldTarget);
}

}
